package com.we.tickets.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.we.tickets.dao.UserDao;
import com.we.tickets.service.UserService;
import com.we.tickets.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public JSONObject login(JSONObject jsonObject) {
        // get password by username
        String username = jsonObject.getString("username");
        String pw_db = userDao.getPasswordByUsername(username);
        if (pw_db == null) {
            return CommonUtil.errorJson("用户名不存在");
        }
        // check if password matches
        String pw = jsonObject.getString("password");
        if (!pw.equals(pw_db)) {
            return CommonUtil.errorJson("密码错误");
        }
        JSONObject userInfo = userDao.getUserInfoByUsername(username);
        return CommonUtil.successJson(userInfo);
    }

    @Override
    public JSONObject signup(JSONObject jsonObject) {
        // check if username already exists
        String username = jsonObject.getString("username");
        String pw_db = userDao.getPasswordByUsername(username);
        if (pw_db != null) {
            return CommonUtil.errorJson("用户名已存在");
        }
        // add user
        userDao.addUser(jsonObject);
        return CommonUtil.successJson();
    }

    @Override
    public JSONObject getAllUsers() {
        List<JSONObject> users = userDao.getAllUsers();
        return CommonUtil.successJson(users);
    }
}
